<template>
  <div v-loading="pageLoading" class="login-container">
    <div v-show="!pageLoading">
      <div class="login-container-bg" :class="isIE!==false?'isIE':''">
        <iframe
          v-if="isIE===false"
          id="login-iframe"
          :src="iframeLink"
          frameborder="0"
          scrolling="no"
          seamless
          class="login-page-iframe"
          @load="iframeLoaded"
        />
        <div v-if="isIE!==false" class="is-ie-box">
          <el-alert
            class="login-ie-tip"
            center
            title="建议使用谷歌浏览器或360极速浏览器进行访问，效果更佳哦~"
            type="warning"
            show-icon
          />
          <el-image :src="loginIEbg" fit="fill" />
        </div>
      </div>
      <div class="login-box-main">
        <div class="login-box-flex">
          <div class="login-words-container">
            <div class="login-container-main-bottom">
              <div>以统一平台规范系统操作</div>
              <div>以规范标准促进技术发展</div>
              <div>以技术能力支撑信息建设</div>
              <div>以信息组网助力企业腾飞</div>
            </div>
          </div>
          <el-form
            ref="loginForm"
            :model="loginForm"
            class="login-form"
            auto-complete="on"
            label-position="left"
            size="medium"
          >
            <div class="title-container">
              <img src="@/assets/login_images/login.png">
              <div class="logo-text">全友呼叫中心运营管理平台</div>
              <div class="logo-text logo-english-text">Call Center Management Platform</div>
            </div>
            <!-- <div class="title-border" /> -->
            <template v-if="!$emergency">
              <el-form-item prop="username">
                <el-input
                  ref="username"
                  v-model="loginForm.username"
                  placeholder="账号"
                  name="username"
                  type="text"
                  tabindex="1"
                  auto-complete="on"
                >
                  <svg-icon slot="prefix" icon-class="jiaoseyonghutouxiangdenglu-line" />
                </el-input>
              </el-form-item>

              <el-tooltip v-model="capsTooltip" content="大写键已开启" placement="right" manual>
                <el-form-item prop="password">
                  <el-input
                    :key="passwordType"
                    ref="password"
                    v-model="loginForm.password"
                    :type="passwordType"
                    placeholder="密码"
                    name="password"
                    tabindex="2"
                    auto-complete="on"
                    @keyup.native="checkCapslock"
                    @blur="capsTooltip = false"
                    @keyup.enter.native="handleLogin"
                  >
                    <svg-icon slot="prefix" icon-class="mimasuo-line" />
                  </el-input>
                  <span class="show-pwd" @click="showPwd">
                    <svg-icon
                      :icon-class="passwordType === 'password' ? 'yanjingbiyan-line' : 'yanjingliulanliang-line'"
                    />
                  </span>
                </el-form-item>
              </el-tooltip>

              <el-form-item prop="phonenum">
                <el-input
                  ref="phonenum"
                  v-model="loginForm.phonenum"
                  placeholder="分机号"
                  name="phonenum"
                  type="text"
                  tabindex="3"
                  auto-complete="on"
                >
                  <svg-icon slot="prefix" icon-class="dianhuaboda-line" />
                </el-input>
              </el-form-item>

              <el-form-item v-if="showCode" class="code-box">
                <el-input
                  ref="verifycode"
                  v-model="loginForm.code"
                  :maxlength="code.len"
                  placeholder="请输入验证码"
                  name="verifycode"
                  type="text"
                  tabindex="3"
                  auto-complete="off"
                  style="width:63%"
                />
                <div class="code-img">
                  <span
                    v-if="code.type === 'text'"
                    class="login-code-img"
                    @click="refreshCode"
                  >{{ code.value }}</span>
                  <img v-else :src="code.src" class="login-code-img" @click="refreshCode">
                </div>
              </el-form-item>

              <el-form-item v-show="showErrorMsg" class="error-msg">
                <div class="error-msg-box">
                  <i class="el-icon-error" />
                  {{ errorMsg }}
                </div>
              </el-form-item>
              <el-form-item class="clearMargin">
                <div class="checkbox-container a-jump">
                  <el-checkbox v-model="rember">记住密码</el-checkbox>
                  <a class="notice-link" :href="findPswUrl">找回密码</a>
                </div>
              </el-form-item>
            </template>
            <template v-else>
              <el-form-item prop="username">
                <el-input
                  ref="username"
                  v-model="loginForm.username"
                  placeholder="平台工号"
                  name="username"
                  type="text"
                  tabindex="1"
                  auto-complete="on"
                >
                  <svg-icon slot="prefix" icon-class="jiaoseyonghutouxiangdenglu-line" />
                </el-input>
              </el-form-item>

              <el-form-item prop="phonenum">
                <el-input
                  ref="phonenum"
                  v-model="loginForm.phonenum"
                  placeholder="分机号"
                  name="phonenum"
                  type="text"
                  tabindex="3"
                  auto-complete="on"
                >
                  <svg-icon slot="prefix" icon-class="dianhuaboda-line" />
                </el-input>
              </el-form-item>

              <el-form-item v-show="showErrorMsg" class="error-msg">
                <div class="error-msg-box">
                  <i class="el-icon-error" />
                  {{ errorMsg }}
                </div>
              </el-form-item>
            </template>
            <el-button
              :loading="loading"
              type="primary"
              class="login-button"
              @click.native.prevent="handleLogin"
            >登 录</el-button>
            <!-- <div class="a-jump"><router-link class="notice-link" to="#">找回密码</router-link></div> -->
            <div class="copyright-box">全友家居©{{ new Date().getFullYear() }}</div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { randomLenNum, detectIE } from '@/utils'
import roamLinks from './components/roamLinks'
import { setStore, getStore } from '@/utils/store'
import { mapMutations } from 'vuex'
const findPswUrl = process.env.VUE_APP_PSWURL
export default {
  name: 'Login',
  data() {
    return {
      findPswUrl, // 找回密码
      rember: false,
      pageLoading: false,
      isIE: false,
      loginIEbg: '',
      loginBgList: [
        require('@/assets/other_images/login_bg1.jpg'),
        require('@/assets/other_images/login_bg2.jpg'),
        require('@/assets/other_images/login_bg3.jpg')
      ],
      iframeLink: '',
      loginForm: {
        username: '',
        password: '',
        code: '',
        randomStr: '',
        phonenum: ''
      },
      code: {
        src: '/code',
        value: '',
        len: 4,
        type: 'image'
      },
      codeUrl: '/code',
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      showErrorMsg: false,
      errorMsg: '',
      showCode: false,
      handNum: 0
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.getAccountPassword()
    this.pageLoading = getStore({ name: 'login_loading', type: 'session' })
    this.iframeLink = roamLinks[Math.floor(Math.random() * 7)]
    // 判断是否为IE浏览器
    this.isIE = detectIE()
    if (this.isIE !== false) {
      this.loginIEbg = this.loginBgList[Math.floor(Math.random() * 3)]
    }
    // --------- 添加跳转登录开始
    if (this.$route.query.username && this.$route.query.password) {
      this.pageLoading = true
      if (this.$route.query.redirect_moduleCode) {
        setStore({
          name: 'redirect_moduleCode',
          content: this.$route.query.redirect_moduleCode
        })
      } else {
        setStore({ name: 'redirect_moduleCode', content: '' })
      }
      const otherLogin = {
        username: this.$route.query.username,
        password: decodeURIComponent(this.$route.query.password),
        code: '',
        randomStr: '',
        isAes: true
      }
      this.$store
        .dispatch('user/login', otherLogin)
        .then(res => {
          const queryData = JSON.parse(JSON.stringify(this.$route.query))
          delete queryData.username
          delete queryData.password
          delete queryData.redirect_url
          if (this.$route.query.redirect_url) {
            this.$router.push({
              path: `/myiframe/urlPath?src=${this.$route.query.redirect_url}`,
              query: queryData
            })
          } else {
            this.$router.push({ path: this.redirect || '/' })
          }
        })
        .catch(err => {
          console.log(err)
        })
      return
    }
    // --------- 添加跳转登录结束
  },
  mounted() {
    if (this.loginForm.username === '') {
      this.$refs.username.focus()
    } else if (this.loginForm.password === '') {
      this.$refs.password.focus()
    }
  },
  methods: {
    ...mapMutations(['SET_PHONE_NUM']),
    // iframe加载完成
    iframeLoaded() {
      try {
        document.getElementById('login-iframe').contentWindow.document
      } catch (err) {
        console.log(err)
      }
    },
    // 刷新验证码
    refreshCode() {
      this.loginForm.code = ''
      this.loginForm.randomStr = randomLenNum(this.code.len, true)
      this.code.type === 'text'
        ? (this.code.value = randomLenNum(this.code.len))
        : (this.code.src = `${this.codeUrl}?randomStr=${this.loginForm.randomStr}`)
    },
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (
          (shiftKey && key >= 'a' && key <= 'z') ||
          (!shiftKey && key >= 'A' && key <= 'Z')
        ) {
          this.capsTooltip = true
        } else {
          this.capsTooltip = false
        }
      }
      if (key === 'CapsLock' && this.capsTooltip === true) {
        this.capsTooltip = false
      }
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      if (!this.$emergency) {
        this.normalLogin()
      } else {
        this.emergencyLogin()
      }
    },
    // 正常登录
    normalLogin() {
      if (this.loginForm.username === '') {
        this.showErrorMsg = true
        this.errorMsg = '请填写账号'
        return false
      } else if (this.loginForm.password.length <= 0) {
        this.showErrorMsg = true
        this.errorMsg = '请填写密码'
        return false
      } else if (this.showCode && this.loginForm.code === '') {
        this.showErrorMsg = true
        this.errorMsg = '请填写验证码'
      } else {
        this.loading = true
        this.$store
          .dispatch('user/login', this.loginForm)
          .then(res => {
            // 记住密码
            if (this.rember) {
              setStore({
                name: 'account',
                content: {
                  username: this.loginForm.username,
                  password: this.loginForm.password
                }
              })
            }
            // 保存分机号
            if (this.loginForm.phonenum) {
              this.SET_PHONE_NUM(this.loginForm.phonenum)
            } else {
              localStorage.removeItem('phonenum')
              this.SET_PHONE_NUM('')
            }
            if (this.$route.query.menuCode) {
              setStore({
                name: 'redirect_moduleCode',
                content: this.$route.query.menuCode
              })
            } else {
              setStore({ name: 'redirect_moduleCode', content: '' })
            }
            let queryData = {}
            if (this.redirect) {
              queryData = JSON.parse(JSON.stringify(this.$route.query))
              delete queryData.redirect
            }
            this.$router.push({ path: this.redirect || '/', query: queryData })
            this.loading = false
            this.showErrorMsg = false
            // 获取用户缓存
          })
          .catch(err => {
            this.handNum = this.handNum + 1
            if (this.handNum >= 3) {
              this.showCode = true
              this.refreshCode()
            }
            this.loading = false
            this.errorMsg =
              err.response && err.response.data ? err.response.data.msg || err.response.data.data || '未知错误' : '未知错误'
            this.showErrorMsg = true
          })
      }
    },
    // 应急登录
    emergencyLogin() {
      // FIXME:应急登录逻辑
      if (this.loginForm.username === '') {
        this.showErrorMsg = true
        this.errorMsg = '请填写平台工号'
        return false
      } else if (this.loginForm.phonenum <= 0) {
        this.showErrorMsg = true
        this.errorMsg = '请填写分机号'
      } else {
        console.log('应急登录请求')
      }
    },
    // 获取记住的密码
    getAccountPassword() {
      const content = getStore({
        name: 'account'
      })
      if (content) {
        this.$set(this.loginForm, 'username', content.username)
        this.$set(this.loginForm, 'password', content.password)
        this.$set(this, 'rember', true)
      }
    }
  }
}
</script>

<style lang="scss">
@import "@/styles/px-rem.scss";

/* reset element-ui css */
.auto-rote-icon {
  position: fixed;
  width: 40px;
  height: 40px;
  top: 18px;
  right: 16px;
  z-index: 100;
  cursor: pointer;
}
.login-container {
  .login-ie-tip {
    position: fixed;
    top: 0;
    border-radius: 0;
    z-index: 10;
    font-size: px2rem(14px);
  }

  .login-code-img {
    display: block;
    height: px2rem(46px);
    width: px2rem(96px);
  }
  .el-input {
    display: inline-block;

    input {
      background: transparent;
      border: 0px;
      border-radius: 4px;
      font-size: px2rem(14px);
      height: px2rem(46px);
      color: rgba(51, 51, 51, 1);
      background-color: #f6fbfa;
      border: 1px solid #cbe8e0;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px #f6fbfa inset !important;
      }
    }
  }
  .is-required {
    margin-top: px2rem(125px);
  }
  .el-tooltip {
    margin-top: px2rem(20px);
  }
  .el-form-item {
    width: px2rem(320px);
    height: px2rem(46px);
    margin-left: px2rem(30px);
    border-radius: 4px;
    // padding: 12px 0px 0px 19px;

    &.error-msg {
      margin-bottom: 0;
    }
    &.code-box {
      margin-bottom: px2rem(10px);
      // display: none;
      .code-img {
        vertical-align: bottom;
        width: 30%;
        margin-left: 5%;
        height: px2rem(46px);
        background: #f7f7f7;
        display: inline-block;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
@import "@/styles/px-rem.scss";
.login-box-main {
  position: fixed;
  width: px2rem(980px);
  min-height: px2rem(460px);
  left: 50%;
  margin-left: px2rem(-490px);
  top: 50%;
  margin-top: px2rem(-230px);
  z-index: 999;
  .login-box-flex {
    display: flex;
    align-items: center;
  }
  .login-words-container {
    position: relative;
    flex: 1;
    background: rgba(37, 10, 10, 0.15);
    min-height: px2rem(460px);
    box-sizing: border-box;
  }
  .login-form {
    position: relative;
    background: rgba(255, 255, 255, 0.8);
    width: px2rem(380px);
    min-height: px2rem(460px);
    box-sizing: border-box;
    overflow: hidden;
    padding-bottom: 20px;

    /deep/ .el-form-item__content {
      line-height: px2rem(50px);
      .svg-icon {
        font-size: px2rem(16px);
        color: #0f9570;
        margin-left: 5px;
      }
    }

    .error-msg {
      height: px2rem(27px);
    }

    .error-msg-box {
      height: px2rem(25px);
      line-height: px2rem(25px);
      background: #ffebee;
      border: 1px solid #ef1f40;
      border-radius: 4px;
      font-size: px2rem(12px);
      text-align: center;
      color: #ef1f40;
    }
    .a-jump {
      font-size: px2rem(12px);
      font-family: Microsoft YaHei;
      font-weight: 400;
      line-height: px2rem(16px);
      color: #666;
      opacity: 1;
      margin-left: px2rem(302px);
      margin-bottom: px2rem(20px);
    }
    .copyright-box {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 10px;
      font-size: px2rem(12px);
      text-align: center;
      color: #c0c0c0;
    }
  }
}

.login-container {
  width: 100%;
  height: 100%;
  overflow: hidden;

  .login-container-bg {
    position: fixed;
    // top: -30px;
    // left: -260px;
    // bottom: -100px;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    &.isIE {
      top: 0;
      left: 0;
      bottom: 0;
    }
    .login-page-iframe {
      position: absolute;
      border: 0;
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
    .is-ie-box {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      overflow: hidden;
      .el-image {
        width: 100%;
        height: 100%;
      }
    }
  }

  .login-container-main-top {
    font-size: px2rem(24px);
    line-height: px2rem(31px);
    color: #fff;
    .words-text {
      margin-bottom: px2rem(20px);
      span {
        margin-right: px2rem(20px);
      }
    }
  }
  .login-container-main-bottom {
    position: absolute;
    left: 0;
    right: 0;
    top: px2rem(130px);
    text-align: center;
    text-align: center;
    font-size: px2rem(22px);
    line-height: px2rem(21px);
    color: #fff;
    letter-spacing: px2rem(7px);
    div {
      margin-bottom: px2rem(32px);
    }
  }

  .tips {
    font-size: px2rem(14px);
    color: #fff;
    margin-bottom: px2rem(10px);

    span {
      &:first-of-type {
        margin-right: px2rem(16px);
      }
    }
  }

  .svg-container {
    width: px2rem(46px);
    height: px2rem(18px);
    font-size: px2rem(13px);
    font-family: PingFangSC-Medium;
    font-weight: 500;
    color: rgba(102, 102, 102, 1);
    line-height: px2rem(18px);
    margin-left: px2rem(14px);
    margin-top: px2rem(15px);
  }

  .title-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    position: relative;
    padding: 0 px2rem(28px);
    // height: px2rem(34px);
    margin-top: px2rem(25px);
    text-align: left;
    img {
      height: px2rem(30px);
    }
    .logo-text {
      color: rgba(234, 85, 33, 1);
      font-size: px2rem(21px);
      padding: px2rem(20px) 0 px2rem(5px);
      padding-left: px2rem(4px);
      font-weight: 600;
      letter-spacing: px2rem(2px);
      flex: 1 0 auto;
      text-align-last: justify;
      text-align: justify;
    }
    .logo-english-text{
      font-size: px2rem(14px);
      padding: px2rem(0px) 0 px2rem(20px);
      padding-left: px2rem(4px);
      color: rgba(136, 136, 136, 1);
      // opacity: 0.5;
    }
  }
  .title-border {
    margin-top: px2rem(15px);
    margin-bottom: px2rem(40px);
    height: 1px;
    background-color: rgba(238, 238, 238, 1);
  }

  .show-pwd {
    position: absolute;
    right: px2rem(10px);
    top: 1px;
    font-size: px2rem(16px);
    cursor: pointer;
    user-select: none;
    .svg-icon {
      color: #ccc !important;
    }
  }

  .thirdparty-button {
    position: absolute;
    right: 0;
    bottom: px2rem(6px);
  }
  .login-button {
    width: px2rem(320px);
    height: px2rem(46px);
    margin-left: px2rem(30px);
    margin-top: px2rem(10px);
    font-size: px2rem(16px);
    margin-bottom: px2rem(20px);
    font-weight: 500;
    font-family: Microsoft YaHei;
  }
}
.clearMargin{
  margin-bottom: 0;
  margin-top: -10px;
  .checkbox-container{
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
  .login-box-main .login-form .a-jump{
    margin-left: 0 !important;
  }
</style>
